<template>
  <div class="app-container">
    <!-- 搜索 -->
    <page-search
        ref="searchRef"
        :search-config="searchModalConfig"
        @query-click="handleQueryClick"
        @reset-click="handleResetClick"
    />
    <!-- 列表 -->
    <page-content
        ref="contentRef"
        :content-config="contentModalConfig"
        @add-click="handleAddClick"
        @edit-click="handleEditClick"
        @search-click="handleSearchClick"
        @toolbar-click="handleToolbarClick"
        @operat-click="handleOperatClick"
    >
      <template #importTypeSlot="scope">
        <span v-if="scope.row.type == '1'">-</span>
        <el-tag type="primary" v-else-if="scope.row[scope.prop] == '0'">增量导入</el-tag>
        <el-tag type="danger" v-else-if="scope.row[scope.prop] == '1'">全量导入</el-tag>
      </template>
      <template #initFieldMapping="scope">
        <el-button :loading="requestStore.isRequestPending" type="primary" size="small"
                   @click="handleFieldMap(scope.row)">字段映射
        </el-button>
      </template>
    </page-content>


    <!-- 新增 -->
    <page-modal
        ref="addModalRef"
        :modal-config="addModalConfig"
        @submit-click="handleSubmitClick">
    </page-modal>
    <!-- 编辑 -->
    <page-modal
        ref="editModalRef"
        :modal-config="editModalConfig"
        @submit-click="handleSubmitClick">
      <template #statusSlot="scope">
        <span v-if="scope.formData[scope.prop] == '0'" style="color: #606266">待初始化</span>
        <el-switch v-else v-model="scope.formData[scope.prop]"
                   active-text="启用"
                   inactive-text="禁用"
                   style="--el-switch-on-color: #13ce66;--el-switch-off-color: #F56C6C;"
                   :inline-prompt="true" active-value="1" inactive-value="2">
        </el-switch>
      </template>
    </page-modal>

    <!--    字段映射配置-->
    <el-dialog :title="fieldMapDialogTitle" v-model="showFieldMappingModal" width="80%" destroy-on-close>
      <div class="table-container">
        <el-button style="float: right;margin-bottom: 10px" type="primary" @click="handleAddOneFieldMap"
                   :disabled="addFieldOption.length<=0">新增一行
        </el-button>
        <el-table :data="fieldMapList" border stripe>
          <el-table-column label="字段名" align="center" prop="fieldName">
            <template #default="scope">
              <div v-if="scope.row.fieldName">{{ scope.row.fieldName }}</div>
              <el-select v-else v-model="scope.row.fieldName" style="width:100%" @change="addFieldOptionChange">
                <el-option v-for="item in addFieldOption" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="excel表头" align="center" prop="showName" show-overflow-tooltip>
            <template #default="scope">
              <el-input type="textarea" autosize v-model="scope.row.showName"/>
            </template>
          </el-table-column>
          <el-table-column label="必填" align="center" prop="notNull" v-if="fieldMapConfigType == '0'">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.notNull"
                  active-value="1"
                  inactive-value="0"
                  :inline-prompt="true"
                  active-text="必填"
                  inactive-text="非必填"
              />
            </template>
          </el-table-column>
          <el-table-column label="排序(越小越靠前)" align="center" prop="sortNum" sortable>
            <template #default="scope">
              <el-input type="number" v-model.lazy="scope.row.sortNum" @blur="sortTable"/>
            </template>
          </el-table-column>
          <el-table-column label="导入时弹框输入" align="center" prop="notNull" v-if="fieldMapConfigType == '0'">
            <template #header>
              <span style="margin-right: 5px">导入时弹框输入</span>
              <el-tooltip content="" effect="light" placement="top">
                <template #content>
                  导入时弹框输入，导入模板将忽略这个字段。
                </template>
                <i-ep-QuestionFilled class="inline-block"/>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-switch
                  v-model="scope.row.importPopFlag"
                  active-value="1"
                  inactive-value="0"
                  :inline-prompt="true"
                  active-text="是"
                  inactive-text="否"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleDeleteOneFieldMap(scope.row.fieldName)">删除本行
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="showFieldMappingModal = false"  :loading="requestStore.isRequestPending">取消</el-button>
        <el-button type="primary" @click="handleSaveFieldMap"  :loading="requestStore.isRequestPending">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type {IOperatData} from "@/hooks/usePage";
import usePage from "@/hooks/usePage";
import contentConfig from "./config/content";
import addConfig from "./config/add";
import editConfig from "./config/edit";
import searchConfig from "./config/search";
import BatchImportExportConfigAPI from "@/api/batchImportExportConfig/index";
import BatchImportExportFieldConfigAPI from "@/api/batchImportExportFieldConfig/index";
import {ElMessage} from "element-plus";
import {useRequestStore} from "@/store";
 

const allTableInfoOptionCache = ref<any[]>(null);
let allTableInfoOptionPromise: Promise<any> | null = null;
const getAllTableInfo = async () => {
  if (allTableInfoOptionCache.value !== null) {
    return allTableInfoOptionCache.value;
  }
  if (!allTableInfoOptionPromise) {
    allTableInfoOptionPromise = new Promise(async (resolve) => {
      const res = await BatchImportExportConfigAPI.service("getAllTableInfo");
      allTableInfoOptionCache.value = res.data;
      resolve(allTableInfoOptionCache.value);
    });
  }
  return allTableInfoOptionPromise;
};


const contentModalConfig = contentConfig({
  getAllTableInfo: getAllTableInfo
});
const addModalConfig = addConfig({
  getAllTableInfo: getAllTableInfo
});
const editModalConfig = editConfig({
  getAllTableInfo: getAllTableInfo
});
const searchModalConfig = searchConfig({
  getAllTableInfo: getAllTableInfo
});
const {
  searchRef,
  contentRef,
  addModalRef,
  editModalRef,
  handleQueryClick,
  handleResetClick,
  handleAddClick,
  handleSubmitClick,
  handleSearchClick,
  handleRefreshClick,
  handleEditClick,
} = usePage();

const requestStore = useRequestStore();
const showFieldMappingModal = ref(false);
const fieldMapList = ref([]);
const fieldInitList = ref([]);
const addFieldOption = ref<{ label: string, value: string }[]>([]);
const fieldMapDialogTitle = ref('');
const fieldMapConfigType = ref('0');

async function handleFieldMap(row: any) {
  fieldMapDialogTitle.value = row.remark + " - 字段映射配置"
  fieldMapConfigType.value = row.type
  const response = await BatchImportExportConfigAPI.service("getTableInfo", {
    tableName: row.tableName,
    configId: row.id
  });
  showFieldMappingModal.value = true
  if (response && response.message) {
    ElMessage({
      message: response.message,
      type: response.status ? 'success' : 'error'
    })

    let configList = response.data.configList || []
    let initList = response.data.initList || []
    fieldInitList.value = initList
    if (configList.length > 0) {
      fieldMapList.value = configList
    } else {
      let fieldMapListTemp = []

      for (let i = 0; i < initList.length; i++) {
        let f = initList[i]
        if (f.type === 'image' || f.type === 'file') {
          //暂时忽略图片类型
          continue
        }
        fieldMapListTemp.push({
          configId: row.id,
          fieldName: f.javaName,
          showName: f.desc,
          notNull: "0",
          importPopFlag: "0",
          sortNum: i * 10,
        })
      }
      fieldMapList.value = fieldMapListTemp as any
    }
    refreshAddFieldOption()
    sortTable()
  }
}

function handleDeleteOneFieldMap(fieldName: string) {
  let fieldMapListTemp = fieldMapList.value || [];
  let deleteIndex = -1
  for (let i = 0; i < fieldMapListTemp.length; i++) {
    if (fieldMapListTemp[i].fieldName == fieldName) {
      deleteIndex = i
      break;
    }
  }
  if (deleteIndex >= 0) {
    fieldMapListTemp.splice(deleteIndex, 1)
  }
  fieldMapList.value = fieldMapListTemp
  refreshAddFieldOption();
}

function checkFieldMap() {
  let fieldMapListTemp = fieldMapList.value || [];
  for (let i = 0; i < fieldMapListTemp.length; i++) {
    if (!fieldMapListTemp[i].fieldName || !fieldMapListTemp[i].showName) {
      ElMessage({
        message: '字段映射配置不允许有空值',
        type: 'error'
      })
      return false
    }
  }
  return true
}

async function handleSaveFieldMap() {
  if (fieldMapList.value.length == 0) {
    ElMessage({
      message: '请先配置字段映射',
      type: 'error'
    })
    return
  } else if (checkFieldMap()) {
    const response = await BatchImportExportFieldConfigAPI.service("addList", {batchImportExportFieldConfigs: JSON.stringify(fieldMapList.value)});
    if (response && response.message) {
      ElMessage({
        message: response.message,
        type: response.status ? 'success' : 'error'
      })
    }
    showFieldMappingModal.value = false
    handleRefreshClick()
  }
}

function handleAddOneFieldMap() {
  let fieldMapListTemp = fieldMapList.value || [];
  fieldMapList.value = []
  let maxSortNum = 0
  for (let i = 0; i < fieldMapListTemp.length; i++) {
    if (fieldMapListTemp[i].sortNum > maxSortNum) {
      maxSortNum = fieldMapListTemp[i].sortNum
    }
  }
  fieldMapListTemp.push({
    configId: fieldMapListTemp[0].configId,
    fieldName: '',
    showName: '',
    notNull: "0",
    importPopFlag: "0",
    sortNum: maxSortNum + 10
  })
  fieldMapList.value = fieldMapListTemp
  refreshAddFieldOption();
}

function refreshAddFieldOption() {
  let hasConfigFieldName: string[] = []
  let fieldMapListTemp = fieldMapList.value || [];
  for (let i = 0; i < fieldMapListTemp.length; i++) {
    hasConfigFieldName.push(fieldMapListTemp[i].fieldName)
  }

  let initList = fieldInitList.value || []
  let addFieldOptionTemp = []
  for (let i = 0; i < initList.length; i++) {
    let f = initList[i]
    if (f.type === 'image' || f.type === 'file') {
      //暂时忽略图片类型
      continue
    }
    if (hasConfigFieldName.indexOf(f.javaName) < 0) {
      addFieldOptionTemp.push({
        value: f.javaName,
        label: f.desc
      })
    }
  }
  addFieldOption.value = addFieldOptionTemp
}

function addFieldOptionChange(value: string) {
  //获取label
  let label = addFieldOption.value.find((item) => item.value === value)?.label;
  let fieldMapListTemp = fieldMapList.value || [];
  for (let i = 0; i < fieldMapListTemp.length; i++) {
    if (fieldMapListTemp[i].fieldName == value) {
      fieldMapListTemp[i].showName = label
      break;
    }
  }
  refreshAddFieldOption()
}

const sortTable = () => {
  let fieldMapListTemp = fieldMapList.value || [];
  fieldMapListTemp.sort((a, b) => a.sortNum - b.sortNum);
  fieldMapList.value = fieldMapListTemp;
};

// 其他工具栏
function handleToolbarClick(name: string) {
  if (name === "import") {

  }
}

// 其他操作列
function handleOperatClick(data: IOperatData) {

}


onMounted(() => {

});


</script>
